<script lang="ts" setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import { useMainStore } from '@/store/main'
import { mlxxMainStore } from '@/store/mlxx'
import { getFldm } from '@/utils/get-fldm'
import axios from '@/request/http'
import { cloneDeep } from 'lodash'
import detailItem from './components/detail-item.vue'
import fjPreview from './components/fj-preview.vue'
import bmDialog from '@/views/gdgl/gdzl/ajwjgl/dialog/bm-dialog.vue'
import gdglService from '@/api/gdgl'
import { useRoute } from 'vue-router'
import rotateDialog from '@/views/gdgl/gdzl/ajwjgl/dialog/rotate-dialog.vue'
import qhbDialog from '@/views/gdgl/gdzl/ajwjgl/dialog/qhb-dialog.vue'
import wztzbDialog from '@/views/gdgl/gdzl/ajwjgl/dialog/wztz-dialog.vue'
import scanDialog from '@/components/scan-dialog.vue'
import { v4 } from 'uuid'

const emit = defineEmits(['wjlxChangeEvent', 'wjlxChange'])
const store = useMainStore()
const mlxxStore = mlxxMainStore()
const route = useRoute()
const bmDialogRef = ref()

// 入参

// 生命周期
onMounted(() => {
  // 获取分类代码
  getSx()
})

// 获取筛选分类代码
const sxList = ref<any[]>([])
const getSx = async () => {
  sxList.value = await getFldm('gd049')
}

// 归档状态查询
// const gdztData = ref<any>({})
// const getAjzt = () => {
//   const params = {
//     ajbh: route.query.ajbh,
//   }
//   gdglService
//     .getAjzt(params)
//     .then((res) => {
//       gdztData.value = res.data
//     })
//     .catch((err) => {
//       !err.isError && ElMessage({ type: 'warning', message: err.message })
//     })
// }

/*
 * 获取标签（分类代码）
 */
const wjlx = ref<any>([])
const getWjlx = async () => {
  wjlx.value = await getFldm('gd001')
}
const wjlxList = computed(() => {
  return wjlx.value.map((item: any) => {
    if (item.dm === 'gd0010001') {
      return {
        ...item,
        mlys: store.$state.nodeTreeData.cj === '1' ? 0 : mlxxStore.mlxxData?.zwys,
        sjys: store.$state.nodeTreeData.cj === '1' ? 0 : mlxxStore.mlxxData?.sjzwys,
      }
    }

    if (item.dm === 'gd0010002') {
      return {
        ...item,
        mlys: store.$state.nodeTreeData.cj === '1' ? 0 : mlxxStore.mlxxData?.qfys,
        sjys: store.$state.nodeTreeData.cj === '1' ? 0 : mlxxStore.mlxxData?.sjqfys,
      }
    }

    if (item.dm === 'gd0010003') {
      return {
        ...item,
        mlys: store.$state.nodeTreeData.cj === '1' ? 0 : mlxxStore.mlxxData?.dgys,
        sjys: store.$state.nodeTreeData.cj === '1' ? 0 : mlxxStore.mlxxData?.sjdgys,
      }
    }
  })
})

const activeName = ref('first')

/*
 * 刷新
 */
const refresh = () => {
  emit('wjlxChange')
  checkboxData.value = []
}

/*
 * 位置调整后更新文件列表
 */
const refreshWjsxh = (target: any) => {
  // 源端更新wjxsh
  wjxqxxList.value = wjxqxxList.value.filter(
    (wj) => !checkboxData.value.find((check) => check.wjbh === wj.wjbh),
  )
  moveEvent()
  // 目标端更新wjxsh
  const params = {
    ajbh: target.ajbh,
    mlbh: target.tzhmlbh,
    wjlxdm: target.tzhwjlxdm,
  }
  wsjzglService
    .queryWjList(params)
    .then((res) => {
      const targetList = res.data
      const params = {
        ajbh: target.ajbh,
        mlbh: target.tzhmlbh,
        wjsh: targetList.map((el: any, i: number) => {
          return {
            wjbh: el.wjbh,
            wjsxh: `${i + 1}`,
          }
        }),
      }
      wsjzglService.updateWjsx(params, route.query.ajbh as string).catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 旋转添加撤回
const refreshCache = () => {
  // cacheList.value.push(cloneDeep(wjxqxxList.value))
  // cacheInde.value = cacheList.value.length - 1
  czShow.value = true
  qycxShow.value = true
  emit('wjlxChange', true)
}

// 操作刷新
const refreshOperate = (index: number) => {
  currentIndex.value = index
  emit('wjlxChangeEvent', wjlxData.value.wjlxdm, null, true)
}

/*
 * 全选
 */
const selectAll = () => {
  checkboxData.value = cloneDeep(wjxqxxList.value)
}

/*
 * 反选
 */
const selectInvert = () => {
  checkboxData.value = cloneDeep(
    wjxqxxList.value.filter(
      (wj: any) => !checkboxData.value.find((el: any) => el.wjbh === wj.wjbh),
    ),
  )
}

/*
 * 删除（成功抛出刷新）
 */
const deleteAjwj = () => {
  ElMessageBox.confirm('是否删除选中的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = {
      ajbh: store.$state.nodeTreeData?.ajbh,
      mlbh: store.$state.nodeTreeData?.bh,
      wjbhList: checkboxData.value.map((item: any) => item.wjbh),
    }
    wsjzglService
      .deleteAjwj(params, route.query.ajbh as string)
      .then(() => {
        ElMessage({ type: 'success', message: '删除成功' })
        emit('wjlxChange')
        checkboxData.value = []
        // 删除操作成功后
        // 操作成功后
        // cacheList.value.push(cloneDeep(wjxqxxList.value))
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

const qycxShow = ref<boolean>(false)
const czShow = ref<boolean>(false)
/*
 * 撤销
 */
const cacheIndexs = ref<number>(0)
const cxDisabled = computed(() => {
  return cacheInde.value === 0 || cacheIndexs.value === 5
})
// 存储恢复数据
const cacheInde = ref<number>(0)
const cancel = () => {
  // 撤销操作
  // const len = cacheList.value.length
  nextTick(() => {
    cacheInde.value--
    cacheIndexs.value++
    wjxqxxList.value = cloneDeep(cacheList.value[cacheInde.value])
    checkboxData.value = wjxqxxList.value.filter((item: any) =>
      checkboxData.value.find((el) => el.wjbh === item.wjbh),
    )
    if (!czShow.value) {
      againUpdateWjsx()
    }
  })
}

/*
 * 恢复
 */
const hfDisabled = computed(() => {
  return cacheList.value.length - 1 === cacheInde.value
})
// 恢复
const restore = () => {
  nextTick(() => {
    cacheInde.value++
    cacheIndexs.value--
    wjxqxxList.value = cloneDeep(cacheList.value[cacheInde.value])
    checkboxData.value = wjxqxxList.value.filter((item: any) =>
      checkboxData.value.find((el) => el.wjbh === item.wjbh),
    )
    againUpdateWjsx()
  })
}

// 恢复原图
const restoreYt = () => {
  nextTick(() => {
    wjxqxxList.value = cloneDeep(cacheList.value[0])
    cacheList.value = [cacheList.value[0]]
    cacheInde.value = 0
    cacheIndexs.value = 0
    checkboxData.value = wjxqxxList.value.filter((item: any) =>
      checkboxData.value.find((el) => el.wjbh === item.wjbh),
    )
    againUpdateWjsx()
  })
}

// 撤销/恢复再次发送请求
const againUpdateWjsx = () => {
  const params = {
    ajbh: store.$state.nodeTreeData?.ajbh as string,
    mlbh: store.$state.nodeTreeData?.bh as string,
    wjsh: wjxqxxList.value.map((el: any) => {
      return {
        wjbh: el.wjbh,
        wjsxh: el.wjsxh,
      }
    }),
  }
  wsjzglService
    .updateWjsx(params, route.query.ajbh as string)
    .then(() => {
      qycxShow.value = false
      // 操作成功后
      emit('wjlxChange', true)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/* 展示详情 */
const currentItem = ref<any>({})
const loadDetail = (item: any) => {
  currentItem.value = { ...item }
}
/* 关闭详情 */
const closeDetail = () => {
  currentItem.value = {}
}

// 页码改变
const currentIndex = ref(0)
const indexChange = (index: any) => {
  // emit('wjlxChangeEvent', wjlxData.value.wjlxdm)
  currentIndex.value = index
  currentItem.value = { ...wjxqxxList.value[index], excludeRevoke: true }
}

// 编目按钮
const catalog = () => {
  bmDialogRef.value.openDialog(checkboxData.value)
}

/*
 * tabs切换
 */
const headerIndex = ref(0)
const wjlxData = ref({
  wjlxdm: 'gd0010001',
  wjlxmc: '正文',
})
const headerClickChange = (value: any, index: number) => {
  if (headerIndex.value === index) return
  headerIndex.value = index
  wjlxData.value.wjlxdm = value.dm
  wjlxData.value.wjlxmc = value.mc
  sxSelectList.value = []
  // emit('wjlxChangeEvent', wjlxData.value.wjlxdm)
}

/**
 * 上传文件
 */
const singleUploadFile = async (files: any, type: string) => {
  const formData = new FormData()
  files.forEach((file: any) => formData.append('files', file.raw))
  formData.append('ajbh', store.$state.nodeTreeData?.ajbh)
  formData.append('mlbh', store.$state.nodeTreeData?.bh)
  formData.append('wjlxdm', wjlxData.value.wjlxdm)
  if (type === 'insert') {
    formData.append('mlsxh', checkboxData.value[0].wjsxh)
  }

  const res = await wsjzglService.uploadAjwj(formData, route.query.ajbh as string).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return {
      code: err.code,
      data: {},
      message: err.message,
    }
  })
  return res || []
}

// 上传文件（成功抛出刷新）
const uploadList = ref([])
const uploadFile = async (e: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const res = await singleUploadFile(e, 'upload')
  if (res.code !== 0) {
    uploadList.value = []
    loading.close()
    return
  }
  setTimeout(() => {
    ElMessage({ type: 'success', message: '上传文件成功' })
    uploadList.value = []
    emit('wjlxChange')
    loading.close()
  }, 3000)
}

const resetHeaderIndex = () => {
  headerIndex.value = 0
  wjlxData.value = {
    wjlxdm: 'gd0010001',
    wjlxmc: '正文',
  }
  sxSelectList.value = []
  sxAll.value = false
}
// 缓存一下所有的操作
const cacheList = ref<any>([])
const wjxqxxList = ref<any[]>([])
const getWjxqxx = (data: any, showCurrent?: boolean, isCache?: boolean) => {
  wjxqxxList.value = data
  if (showCurrent) {
    currentItem.value = data[currentIndex.value]
  } else {
    currentItem.value = {}
  }
  // currentItem.value = data[currentIndex.value]
  // checkboxData.value = []
  getWjlx()
  // 缓存
  if (isCache) {
    if (qycxShow.value) {
      cacheList.value.push(cloneDeep(wjxqxxList.value))
      cacheInde.value = cacheList.value.length - 1
    }
    checkboxData.value = data.filter((item: any) =>
      checkboxData.value.find((el) => el.wjbh === item.wjbh),
    )
  } else {
    cacheList.value = [cloneDeep(data)]
    cacheInde.value = 0
    cacheIndexs.value = 0
    checkboxData.value = []
  }
}

// 复选框绑定数据
const checkboxData = ref<any[]>([])

const checkChange = (data: any, e: Event) => {
  e.preventDefault()
  e.stopPropagation()
  const checkboxIndex = checkboxData.value.findIndex((el) => el.wjbh === data.wjbh)
  lastSelectedItem.value = data
  if (checkboxIndex >= 0) {
    checkboxData.value.splice(checkboxIndex, 1)
  } else {
    checkboxData.value.push(data)
  }
  // checkboxData.value = data
  // checkboxData.value.sort((a, b) => a.wjsxh - b.wjsxh)
}

const moveEvent = () => {
  const params = {
    ajbh: store.$state.nodeTreeData?.ajbh as string,
    mlbh: store.$state.nodeTreeData?.bh as string,
    wjsh: wjxqxxList.value.map((el: any, i: number) => {
      return {
        wjbh: el.wjbh,
        wjsxh: `${i + 1}`,
      }
    }),
  }
  wsjzglService
    .updateWjsx(params, route.query.ajbh as string)
    .then(() => {
      cacheIndexs.value = 0
      czShow.value = false
      qycxShow.value = true
      // 操作成功后
      emit('wjlxChange', true)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
const uploadInput = ref()
const uploadRef = ref()
const acceptWhiteList = ref<any[]>(['.pdf', '.jpg', '.jpeg', '.png', '.bmp', '.ofd'])
const uploadChange = (file: any, files: any[]) => {
  const lastStr = file.raw.name.slice(file?.raw.name.lastIndexOf('.'))
  uploadInput.value = document.getElementsByName('uploadFileInput')[0]
  if (!acceptWhiteList.value.includes(lastStr?.toLowerCase())) {
    uploadRef.value?.handleRemove(file)
    return ElMessage.warning(
      `不支持上传${lastStr}格式的文件，现只支持上传.pdf、.ofd、.jpg、.jpeg、.png、.bmp类型的文件`,
    )
  }
  if (uploadInput.value.files.length === files.length) {
    uploadFile(files)
  }
}
// 文件上传方法
const httpRequest = (params: any) => {
  if (params.file.size === 0) {
    ElMessage.warning('存在文件大小为0,请核实文件内容')
    return
  }
  uploadFile(params.file)
}

// 前移动
const moveUp = () => {
  const index = wjxqxxList.value.findIndex((item: any) => item === checkboxData.value[0])
  if (index === 0) return
  wjxqxxList.value.splice(index, checkboxData.value.length)
  wjxqxxList.value.splice(index - 1, 0, ...checkboxData.value)
  moveEvent()
}

// 后移动
const moveDown = () => {
  const index = wjxqxxList.value.findIndex((item: any) => item === checkboxData.value[0])
  if (index === wjxqxxList.value.length - 1) return
  wjxqxxList.value.splice(index, checkboxData.value.length)
  wjxqxxList.value.splice(index + 1, 0, ...checkboxData.value)
  moveEvent()
}

// 插入
const insertInput = ref()
const insertList = ref([])
const insertChange = (file: any, files: any[]) => {
  const lastStr = file.raw.name.slice(file?.raw.name.lastIndexOf('.'))
  if (!acceptWhiteList.value.includes(lastStr?.toLowerCase()))
    return ElMessage.warning(
      `不支持上传${lastStr}格式的文件，现只支持上传.pdf、.ofd、.jpg、.jpeg、.png、.bmp类型的文件`,
    )
  insertInput.value = document.getElementsByName('insertFileInput')[0]
  if (insertInput.value.files.length === files.length) {
    insertRequest(files)
  }
}
const insertRequest = async (files: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const res = await singleUploadFile(files, 'insert')
  if (res.code !== 0) {
    insertList.value = []
    loading.close()
    return
  }

  setTimeout(() => {
    ElMessage({ type: 'success', message: '插入成功' })
    insertList.value = []
    emit('wjlxChange')
    loading.close()
  }, 3000)
}

// 替换
const fileList = ref<any>([])
const replaceLoading = ref()
const updateWjnr = () => {
  const inputParams = {
    ajbh: store.nodeTreeData.ajbh as string,
    mlbh: store.nodeTreeData.bh as string,
    dthwjbhList: checkboxData.value.map((el) => el.wjbh),
    wjxxList: wjxhList.value.map((el: any) => ({
      wjmc: el.wjmc,
      wjxh: el.wjxh,
    })),
  }
  wsjzglService
    .updateWjnr(inputParams, route.query.ajbh as string)
    .then(() => {
      emit('wjlxChange', wjlxData.value.wjlxdm)
      replaceLoading.value.close()
      fileList.value = []
      wjxhList.value = []
      count.value = 0
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
      replaceLoading.value.close()
      fileList.value = []
      wjxhList.value = []
      count.value = 0
    })
}
// 记录一下上传成功的数据
const count = ref(0)
const wjxhList = ref<any>([])
// const replaceInput = ref()
// const replaceChange = (file: any, files: any[]) => {
//   replaceInput.value = document.getElementsByName('replaceFileInput')[0]
//   const flat = Array.from(replaceInput.value.files)?.every(
//     (item: any) => !!acceptWhiteList.value.find((el) => el === item.type.split('/')[1]),
//   )
//   if (!flat) {
//     return ElMessage.warning(
//       `有包含不支持上传格式的文件，现只支持上传.pdf、.ofd、.jpg、.jpeg、.png、.bmp类型的文件`,
//     )
//   }
//   replaceRequest(file)
// }

const replaceRequest = async (params: any) => {
  if (params.file.size === 0) {
    ElMessage.warning('存在文件大小为0,请核实文件内容')
    return
  }
  replaceLoading.value = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const formData = new FormData()

  formData.append('file', params.file)
  gdglService
    .singleUploadFile(formData, route.query.ajbh as string)
    .then((res) => {
      count.value++
      wjxhList.value.push(cloneDeep({ wjxh: res.data.wjxh, wjmc: params.file.name }))
      if (count.value === fileList.value.length) {
        updateWjnr()
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
      fileList.value = []
      wjxhList.value = []
      count.value = 0
      replaceLoading.value.close()
    })
}

// 扫描参数
const scanRef = ref()
const openScan = () => {
  scanRef.value.openDialog()
}

const sokect = ref()
// 扫描文件
const scanLoading = ref(false)
const startScan = () => {
  scanLoading.value = true
  const url = window.SCANIP.replace('http://', '')
  sokect.value = new WebSocket(`ws://${url}/scanner/wss/${v4()}`)
  sokect.value.onmessage = function (event: any) {
    const msg = JSON.parse(event.data)
    if (msg.status === 'sys_1') {
      scanRef.value.openDialog(true)
    } else if (msg.status === 'sys_2' && msg.data.scanStatus === 1) {
      // emit('scanOver', msg.data.data, true)
      scanOver(msg.data.data, true)
    } else if (msg.status === 'sys_3' && msg.data.scanStatus === 3) {
      scanOver({}, false)
      // emit('scanOver', {}, false)
    }
  }

  sokect.value.onerror = function (error: any) {
    console.log(error)
    scanOver(error, false)
    // emit('scanOver', error, false)
    sokect.value.close()
  }

  const params = JSON.stringify({
    operationInstructions: 'start',
    data: '',
  })

  sokect.value.send(params)
}

/**
 * base64转换file
 */
const base64ToFile = (base64: any, fileName: string) => {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  console.log(mime)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}
// 扫描结束，返回base64
const scanOver = (data: any, success: boolean) => {
  scanLoading.value = false
  if (success) {
    ElMessage.success('扫描成功，开始上传')
    const file = base64ToFile('data:image/jpg;base64,' + data.fileBase64Str, data.fileName)
    uploadFile([{ raw: file }])
  } else {
    ElMessage.error('请检查扫描设备是否正常连接！')
  }
}
// 去黑边
const qhbRef = ref()
const clearBlackBorder = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const params = {
    ajbh: store.nodeTreeData.ajbh,
    bmsah: route.query.bmsah,
    gdbh: route.query.gdbh,
    mlbh: store.nodeTreeData.bh,
    wjbhList: checkboxData.value.map((el: any) => el.wjbh),
  }
  wsjzglService
    .pictureQhbG(params, route.query.ajbh as string)
    .then(() => {
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // cacheList.value.push(cloneDeep(wjxqxxList.value))
      // cacheInde.value = cacheList.value.length - 1
      // emit('wjlxChange', true)
      czShow.value = true
      qycxShow.value = true
      emit('wjlxChange', true)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.close()
    })
}

// 纠偏
const correctClick = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const params = {
    ajbh: store.nodeTreeData.ajbh,
    bmsah: route.query.bmsah,
    gdbh: route.query.gdbh,
    mlbh: store.nodeTreeData.bh,
    wjbhList: checkboxData.value.map((el) => el.wjbh),
  }
  wsjzglService
    .pictureJpG(params, route.query.ajbh as string)
    .then(() => {
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // cacheList.value.push(cloneDeep(wjxqxxList.value))
      // cacheInde.value = cacheList.value.length - 1
      czShow.value = true
      qycxShow.value = true
      emit('wjlxChange', true)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.close()
    })
}

const rotateRef = ref()
// 旋转
const rotateClick = () => {
  rotateRef.value.openDialog(checkboxData.value)
}

// 位置调整
const wztzRef = ref()
const wztzClick = () => {
  wztzRef.value.openDialog(checkboxData.value)
}

const lastSelectedItem = ref()

// 点击
const checkboxSelect = (item: any, e: any) => {
  e.preventDefault()
  if (e.shiftKey) {
    const start = wjxqxxList.value.indexOf(lastSelectedItem.value)
    const end = wjxqxxList.value.indexOf(item)
    const selectedItems = wjxqxxList.value.slice(Math.min(start, end), Math.max(start, end) + 1)
    checkboxData.value = selectedItems
  } else if (e.ctrlKey) {
    const checkboxIndex = checkboxData.value.findIndex((el) => el.wjbh === item.wjbh)
    lastSelectedItem.value = item
    if (checkboxIndex >= 0) {
      checkboxData.value.splice(checkboxIndex, 1)
    } else {
      checkboxData.value.push(cloneDeep(item))
    }
  } else {
    const checkboxIndex = checkboxData.value.findIndex((el) => el.wjbh === item.wjbh)
    lastSelectedItem.value = item
    if (checkboxIndex >= 0) {
      checkboxData.value.splice(checkboxIndex, 1)
    } else {
      checkboxData.value = [item]
    }
  }

  // if (e.shiftKey) {
  //   const lastSelectedIndex = wjxqxxList.value.findIndex((selected: any) => selected === item)
  //   const currentIndex = wjxqxxList.value.indexOf(item)
  //   const startIndex = Math.min(lastSelectedIndex, currentIndex)
  //   const endIndex = Math.max(lastSelectedIndex, currentIndex)
  //   checkboxData.value = wjxqxxList.value.slice(startIndex, endIndex + 1)
  // }
}

// 筛选
const sxSelectList = ref<any[]>([])
// 全选
const sxAll = ref(false)
const indeterminate = ref(false)
watch(
  () => sxAll.value,
  (val) => {
    if (val || sxSelectList.value.length < sxList.value.length) {
      sxSelectList.value = sxList.value
    } else {
      sxSelectList.value = []
    }
  },
)

watch(
  () => sxSelectList,
  () => {
    if (sxSelectList.value.length > 0 && sxSelectList.value.length < sxList.value.length) {
      indeterminate.value = true
    } else {
      indeterminate.value = false
    }
    if (sxSelectList.value.length === sxList.value.length) sxAll.value = true
    emit('wjlxChangeEvent', wjlxData.value.wjlxdm, sxSelectList.value)
  },
  {
    deep: true,
  },
)

const isUploadShow = computed(() => {
  if (mlxxStore.gdztData?.tgztdm === 'gd0150009' && mlxxStore.gdztData?.gdjddm === 'gd0180009') {
    return true
  }
  if (
    !mlxxStore.gdztData?.gdjddm ||
    mlxxStore.gdztData?.gdjddm === 'gd0180001' ||
    mlxxStore.gdztData?.gdjddm === 'gd0180005'
  ) {
    return true
  }

  if (mlxxStore.gdztData?.tglxdm === 'gd0040001') {
    return true
  }
  return false
})

const isEditShow = computed(() => {
  if (
    !mlxxStore.gdztData?.gdjddm ||
    mlxxStore.gdztData?.gdjddm === 'gd0180001' ||
    mlxxStore.gdztData?.gdjddm === 'gd0180005' ||
    mlxxStore.gdztData?.gdjddm === 'gd0180010'
  ) {
    return true
  }

  if (
    mlxxStore.gdztData?.tglxdm === 'gd0040002' &&
    mlxxStore.gdztData?.ajlxdm.includes('gd0100001') &&
    wjxqxxList.value.some((item: any) => item.wjlydm === 'gd0300001')
  ) {
    return true
  }

  if (
    mlxxStore.gdztData?.tglxdm === 'gd0040002' &&
    mlxxStore.gdztData?.ajlxdm.includes('gd0100002') &&
    wjxqxxList.value.some((item: any) => item.wjlydm === 'gd0300002')
  ) {
    return true
  }
  return false
})

const isDeleteShow = computed(() => {
  if (
    !mlxxStore.gdztData?.gdjddm ||
    mlxxStore.gdztData?.gdjddm === 'gd0180001' ||
    mlxxStore.gdztData?.gdjddm === 'gd0180005'
  ) {
    return true
  }

  if (
    mlxxStore.gdztData?.tglxdm === 'gd0040003' &&
    mlxxStore.gdztData?.ajlxdm.includes('gd0100001') &&
    wjxqxxList.value.some((item: any) => item.wjlydm === 'gd0300001')
  ) {
    return true
  }

  if (
    mlxxStore.gdztData?.tglxdm === 'gd0040003' &&
    mlxxStore.gdztData?.ajlxdm.includes('gd0100002') &&
    wjxqxxList.value.some((item: any) => item.wjlydm === 'gd0300002')
  ) {
    return true
  }
  return false
})
const ajxqLabel = computed(() => {
  if (store.nodeTreeData?.cj === '1') {
    return store.nodeTreeData?.mc
  } else if (store.nodeTreeData?.cj === '2') {
    if (store.nodeTreeData?.fbh === store.zjNode?.bh) return store.zjNode?.mc
    else if (store.nodeTreeData?.fbh === store.fjNode?.bh) return store.fjNode?.mc
    else return store.jzsmDbmNode?.mc
  } else if (store.nodeTreeData?.cj === '3') {
    return '附件'
  }
  return store.nodeTreeData?.mc
})

const qwssWj = (wjbh: string) => {
  return store.nodeTreeData?.wjbhList?.includes(wjbh)
}
// 预览
defineExpose({ resetHeaderIndex, getWjxqxx })
</script>
<template>
  <div class="container">
    <el-tabs v-model="activeName" class="demo-tabs" type="card">
      <el-tab-pane :label="ajxqLabel" name="first">
        <div v-if="ajxqLabel !== '附件'" class="content">
          <!-- 头部 -->
          <div class="top">
            <div class="top-title">
              <div class="topLeft">
                <img src="@/assets/images/yjqqs.png" alt="" />
                <p>{{ store.$state.nodeTreeData?.mc }}</p>
              </div>
            </div>
            <!-- <div class="topRight">
              <el-input placeholder="请输入查询关键字" suffix-icon="Search" />
            </div> -->

            <!-- 按钮 -->
            <div class="buttomGroup">
              <div class="rowbutton">
                <button class="btn_operation" @click="openScan">
                  <div class="btn-smcs"></div>
                  扫描参数
                </button>
              </div>

              <div class="rowbutton">
                <button class="btn_operation" @click="refresh">
                  <div class="btn-sx" title="刷新"></div>
                  <span>刷新</span>
                </button>

                <button class="btn_operation" @click="selectAll">
                  <div class="btn-qx" title="全选"></div>
                  <span>全选</span>
                </button>

                <button class="btn_operation" @click="selectInvert">
                  <div class="btn-fx" title="反选"></div>
                  <span>反选</span>
                </button>
                <button
                  class="btn_operation"
                  @click="deleteAjwj"
                  :disabled="
                    !(
                      ((isDeleteShow && store.nodeTreeData?.cj === '2') ||
                        store.nodeTreeData?.mc === '待编目材料') &&
                      checkboxData.length &&
                      mlxxStore.isUnlockReadOnly
                    )
                  "
                >
                  <div class="btn-sc" title="删除"></div>
                  <span>删除</span>
                </button>

                <button
                  class="btn_operation"
                  @click="moveUp"
                  :disabled="
                    !(
                      ((isEditShow && store.nodeTreeData?.cj === '2') ||
                        store.nodeTreeData?.mc === '待编目材料') &&
                      checkboxData.length === 1 &&
                      checkboxData[0].wjsxh !== '1' &&
                      mlxxStore.isUnlockReadOnly
                    )
                  "
                >
                  <div class="btn-qy" title="前移"></div>
                  <span>前移</span>
                </button>
                <button
                  class="btn_operation"
                  @click="moveDown"
                  :disabled="
                    !(
                      ((isEditShow && store.nodeTreeData?.cj === '2') ||
                        store.nodeTreeData?.mc === '待编目材料') &&
                      checkboxData.length === 1 &&
                      checkboxData[0].wjsxh !== wjxqxxList[wjxqxxList.length - 1].wjsxh &&
                      mlxxStore.isUnlockReadOnly
                    )
                  "
                >
                  <div class="btn-hy" title="后移"></div>
                  <span>后移</span>
                </button>
                <button
                  class="btn_operation"
                  @click="wztzClick"
                  :disabled="
                    !(
                      ((isEditShow && store.nodeTreeData?.cj === '2') ||
                        store.nodeTreeData?.mc === '待编目材料') &&
                      checkboxData.length &&
                      mlxxStore.isUnlockReadOnly
                    )
                  "
                >
                  <div class="btn-wztz" title="位置调整"></div>
                  <span>位置调整</span>
                </button>

                <el-upload
                  name="insertFileInput"
                  style="padding: 0; margin-left: 6px"
                  multiple
                  :auto-upload="false"
                  :on-change="insertChange"
                  :http-request="insertRequest"
                  :show-file-list="false"
                  :accept="'.pdf,.jpg,.jpeg,.png,.bmp,.ofd'"
                  v-model:file-list="insertList"
                  :disabled="
                    !(
                      ((isEditShow && store.nodeTreeData?.cj === '2') ||
                        store.nodeTreeData?.mc === '待编目材料') &&
                      checkboxData.length === 1 &&
                      mlxxStore.isUnlockReadOnly
                    )
                  "
                >
                  <button
                    class="btn_operation"
                    :disabled="
                      !(
                        ((isEditShow && store.nodeTreeData?.cj === '2') ||
                          store.nodeTreeData?.mc === '待编目材料') &&
                        checkboxData.length === 1 &&
                        mlxxStore.isUnlockReadOnly
                      )
                    "
                  >
                    <div class="btn-hf" title="插入"></div>
                    <span>插入</span>
                  </button>
                </el-upload>
                <!-- action="action" -->
                <el-upload
                  name="replaceFileInput"
                  style="padding: 0; margin-left: 10px"
                  multiple
                  :http-request="replaceRequest"
                  :show-file-list="false"
                  :accept="'.pdf,.png,.jpeg,.jpg,.bmp,.ofd'"
                  v-model:file-list="fileList"
                >
                  <button
                    class="btn_operation"
                    :disabled="
                      !(
                        ((isEditShow && store.nodeTreeData?.cj === '2') ||
                          store.nodeTreeData?.mc === '待编目材料') &&
                        checkboxData.length &&
                        mlxxStore.isUnlockReadOnly
                      )
                    "
                  >
                    <div class="btn-hf" title="替换"></div>
                    <span>替换</span>
                  </button>
                </el-upload>
                <button
                  style="margin-left: 6px"
                  :disabled="
                    !(
                      store.nodeTreeData?.mc === '待编目材料' &&
                      isEditShow &&
                      checkboxData.length
                    ) || !mlxxStore.isUnlockReadOnly
                  "
                  class="btn_operation"
                  @click="catalog"
                >
                  <div class="btn-zzml" title="编目"></div>
                  <span>编目</span>
                </button>

                <!-- <el-popover placement="bottom" :width="100" trigger="hover">
                  <ul class="export-excel">
                    <li @click="rotateClick">旋转</li>
                    <li @click="correctClick">纠偏</li>
                    <li @click="clearBlackBorder">去黑边</li>
                  </ul>
                  <template #reference>
                    <button
                      class="btn_operation"
                      style="margin-left: 6px"
                      :disabled="
                        !(
                          ((isEditShow && store.nodeTreeData?.cj === '2') ||
                            store.nodeTreeData?.mc === '待编目材料') &&
                          checkboxData.length &&
                          mlxxStore.isUnlockReadOnly
                        )
                      "
                    >
                      <div class="btn-bj" title="编辑"></div>
                      <span>编辑</span>
                    </button>
                  </template>
                </el-popover> -->

                <!-- <button
                  class="btn_operation"
                  @click="cancel"
                  :disabled="
                    !(
                      (isEditShow && store.nodeTreeData?.cj === '2') ||
                      store.nodeTreeData?.mc === '待编目材料'
                    ) || cxDisabled
                  "
                >
                  <div class="btn-chexiao" title="撤销"></div>
                  <span>撤销</span>
                </button>
                <button
                  class="btn_operation"
                  @click="restore"
                  :disabled="
                    !(
                      (isEditShow && store.nodeTreeData?.cj === '2') ||
                      store.nodeTreeData?.mc === '待编目材料'
                    ) || hfDisabled
                  "
                >
                  <div class="btn-huifu" title="恢复"></div>
                  <span>恢复</span>
                </button>

                <button
                  class="btn_operation"
                  @click="restoreYt"
                  :disabled="
                    !(
                      (isEditShow && store.nodeTreeData?.cj === '2') ||
                      store.nodeTreeData?.mc === '待编目材料'
                    ) || cxDisabled
                  "
                >
                  <div class="btn-huifuyuantu" title="恢复原图"></div>
                  <span>恢复原图</span>
                </button> -->

                <el-popover
                  popper-class="screen-popover"
                  placement="bottom"
                  :width="200"
                  trigger="hover"
                >
                  <ul class="screen-style">
                    <li class="sx-all">
                      <el-checkbox v-model="sxAll" :indeterminate="indeterminate">全选</el-checkbox>
                    </li>
                    <li v-for="item in sxList" :key="item.dm">
                      <el-checkbox-group v-model="sxSelectList">
                        <el-checkbox :value="item">{{ item.mc }}</el-checkbox>
                      </el-checkbox-group>
                    </li>
                  </ul>
                  <template #reference>
                    <!--  :disabled="
                      !(
                        ((isEditShow && store.nodeTreeData?.cj === '2') ||
                          store.nodeTreeData?.mc === '待编目材料') &&
                        checkboxData.length
                      )
                    " -->
                    <button class="btn_operation" style="margin-left: 6px">
                      <div class="btn-shaixuan" title="筛选"></div>
                      <span>筛选</span>
                    </button>
                  </template>
                </el-popover>
              </div>
            </div>
          </div>

          <!-- 内容区域 -->
          <div class="center">
            <!-- {{ cacheIndexs }}
            {{ cacheInde }} -->
            <div class="headerButtomGroup" v-if="store.nodeTreeData?.cj === '2'">
              <button
                v-for="(item, index) in wjlxList"
                :key="item.dm"
                class="header-text"
                :class="headerIndex === index ? 'header-avtive' : ''"
                @click="headerClickChange(item, index)"
              >
                {{ item.mc }}
                <span :style="{ color: item.sjys === item.mlys ? '' : 'red' }"
                  >({{ item.sjys }}/{{ item.mlys }})</span
                >
              </button>
            </div>
            <div class="writingsBox" v-if="wjxqxxList.length">
              <div class="writingsItem" v-for="item in wjxqxxList" :key="item.wjbh">
                <div
                  class="item-content"
                  :class="{ qwjs: qwssWj(item.wjbh) }"
                  @click="checkboxSelect(item, $event)"
                  :style="{
                    border: checkboxData.some((el) => el.wjbh === item.wjbh)
                      ? '3px solid #409eff'
                      : '',
                  }"
                >
                  <div class="content-header">
                    <el-checkbox-group v-model="checkboxData" @click="checkChange(item, $event)">
                      <el-checkbox :value="item"></el-checkbox>
                    </el-checkbox-group>
                    <div>
                      <img
                        v-if="
                          (store.nodeTreeData?.cj === '2' || store.nodeTreeData?.cj === '1') &&
                          item.wjlydm === 'gd0300001'
                        "
                        src="/src/assets/images/xswjwyz.png"
                        style="margin-right: 5px"
                      />
                      <img
                        v-if="
                          (store.nodeTreeData?.cj === '2' || store.nodeTreeData?.cj === '1') &&
                          item.wjlydm === 'gd0300002'
                        "
                        src="/src/assets/images/xxwj.png"
                      />
                    </div>
                    <!-- <img
                      v-if="data.cj === '2' && data.sfdzajml === 'Y'"
                      style="margin-right: 5px"
                      src="/src/assets/images/xswjwyz.png"
                      alt=""
                    />
                    <img
                      v-if="data.cj === '2' && (data.sfzzajml === 'Y' || !data.sfzzajml)"
                      src="/src/assets/images/xxwj.png"
                      alt=""
                    /> -->
                  </div>
                  <div class="content-img" @dblclick.stop="loadDetail(item)">
                    <img
                      :src="
                        axios.defaults.baseURL +
                        '/fpi/wjfw/download?wjbh=' +
                        item.jpgwjxh +
                        '&date=' +
                        Date.now()
                      "
                    />
                  </div>
                  <div class="content-footer" v-if="item.jcztmc && item.jcztdm !== 'gd0490001'">
                    {{ item.jcztmc }}
                  </div>
                </div>
                <div class="pageNumber">
                  {{ item.wjsxh }}
                </div>
              </div>
            </div>
            <el-empty v-else class="noMessage"></el-empty>
          </div>
          <!-- 底部按钮 -->
          <!-- v-if="gdztData.gdjddm !== 'gd0180006'" -->
          <div
            class="bottomButton"
            v-if="
              (store.nodeTreeData?.cj !== '1' || store.nodeTreeData?.mc === '待编目材料') &&
              isEditShow &&
              store.nodeTreeData?.fbh &&
              mlxxStore.isUnlockReadOnly
            "
          >
            <el-button type="primary" :loading="scanLoading" @click="startScan">扫描文件</el-button>
            <!-- :disabled="disabled" -->
            <el-upload
              ref="uploadRef"
              name="uploadFileInput"
              style="padding: 0; margin-left: 6px"
              multiple
              :auto-upload="false"
              :on-change="uploadChange"
              :http-request="httpRequest"
              :show-file-list="false"
              :accept="'.pdf,.jpg,.jpeg,.png,.bmp,.ofd'"
              v-model:file-list="uploadList"
            >
              <el-button type="primary">上传文件</el-button>
            </el-upload>
            <div class="secret">*严禁传输涉密信息</div>

            <!-- <el-button type="primary" @click="uploadClick">上传文件</el-button> -->
            <!-- <input style="display: none" type="file" @change="uploadFile" ref="file" /> -->
          </div>
        </div>
        <div v-if="Object.keys(currentItem).length && ajxqLabel !== '附件'">
          <!-- 展示详情 -->
          <detail-item
            :current-item="currentItem"
            class="detail-wrapper"
            @close="closeDetail"
            :wjxqxxList="wjxqxxList"
            @indexChange="indexChange"
            @refreshOperate="refreshOperate"
            v-if="currentItem.wjbh"
          ></detail-item>
        </div>
        <div v-show="ajxqLabel === '附件'" class="detail-wrapper">
          <fj-preview :currentItem="store.nodeTreeData"></fj-preview>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编目弹窗 -->
    <bmDialog ref="bmDialogRef" @refresh="refresh"></bmDialog>
    <!-- 去黑边 -->
    <qhbDialog ref="qhbRef" @refresh="refreshCache"></qhbDialog>
    <!-- 旋转弹窗 -->
    <rotateDialog ref="rotateRef" @refresh="refreshCache"></rotateDialog>
    <!-- 位置调整 -->
    <wztzbDialog ref="wztzRef" @refresh="refreshWjsxh"></wztzbDialog>
    <!-- 扫描参数 -->
    <scanDialog ref="scanRef" :sokect="sokect"></scanDialog>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .content {
    width: 100%;
    height: 100%;
    // padding: 5px;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      flex-direction: column;
      height: 82px;
      border-bottom: 1px solid #dae4f1;
      padding-bottom: 5px;
      margin-bottom: 5px;
      .top-title {
        height: 28px;
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .topLeft {
          display: flex;

          img {
            padding-right: 5px;
          }
          p {
            font-weight: 600;
          }
        }
      }
    }
    .buttomGroup {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
      .rowbutton {
        display: flex;
      }
      .btn_operation {
        padding: 0 8px;
        min-width: 64px;
        white-space: nowrap;
      }
      .btn_operation + .btn_operation {
        margin-left: 6px;
      }
      @media screen and (max-width: 1480px) {
        .btn_operation {
          min-width: 34px;
          div {
            margin-right: 0;
          }
          span {
            display: none;
          }
        }
      }
    }

    .center {
      padding: 15px;
      background-color: #f7f8f9;
      flex: 1;
      height: calc(100% - 200px);
      display: flex;
      flex-direction: column;
      .headerButtomGroup {
        .header-text {
          color: #4a76ab;
        }
        .header-text + .header-text {
          margin-left: 10px;
        }
        .header-avtive {
          color: #fff;
          background-color: #3c89d0;
        }
      }

      .writingsBox {
        overflow-y: auto;
        max-height: 100%;
        display: flex;
        flex-wrap: wrap;
        padding-top: 10px;
        padding-left: 10px;
        .writingsItem {
          width: 212px;
          padding: 0 16px 10px 0;
          display: flex;
          flex-direction: column;

          .item-content {
            display: flex;
            flex-direction: column;
            flex: 1;
            flex-shrink: 0;
            background-color: #fff;
            box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            border: 3px solid transparent;
            &.qwjs {
              // border-color: #ffd76a;
              box-shadow: 0px 0px 0px 5px #ffd76a;
            }
            .content-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 0 10px;
              img {
                width: 14px;
                height: 16px;
              }
            }

            .content-img {
              padding: 0 10px;
              flex: 1;
              flex-shrink: 0;
              background-color: #fff;

              & > img {
                width: 100%;
                height: 212px;
              }
            }

            .content-footer {
              width: 100%;
              text-align: center;
              padding: 5px 0;
              background-color: #f7c863;
            }
          }

          .pageNumber {
            height: 26px;
            line-height: 26px;
            text-align: center;
          }
        }
      }

      .noMessage {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .bottomButton {
      display: flex;
      align-items: center;
      margin-top: 10px;
      .secret {
        margin-left: 10px;
        color: red;
      }
    }
  }
}

.export-excel {
  li {
    text-align: center;
    height: 30px;
    line-height: 30px;
    cursor: pointer;
    &:hover {
      background-color: #ecf5ff;
      color: #266df5;
    }
  }
}

.screen-style {
  li {
    display: flex;
    align-items: center;
    padding: 0 10px;
    cursor: pointer;
    &:hover {
      background-color: #ecf5ff;
      color: #266df5;
    }
    & > .el-checkbox-group,
    .el-checkbox {
      width: 100%;
      .el-checkbox {
        width: 100%;
      }
    }
    &.sx-all {
      border-bottom: 1px solid #dcdcdc;
    }
  }
}

.detail-wrapper {
  width: 100%;
  height: 100%;
  padding: 10px;
  background-color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 999;
}
</style>
